var nodeList = [];
var planTreeSetting;
var planTree = {
        /**
         *初始化tree
         */
        initTree: function () {
            var rightSetting = {
                view: {
                    fontCss: getFontCss,
                    selectedMulti: false
                },
                check: {
                    enable: false
                },
                edit: {},
                data: {
                    keep: {
                        parent: true,
                        leaf: true
                    },
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onDblClick: planTree.moveCaseToLeft
                }
            };
            $.fn.zTree.init($("#rightTree"), rightSetting);
            var leftSetting = {
                view: {
                    fontCss: getFontCss,
                    selectedMulti: false
                },
                check: {
                    enable: false
                },
                edit: {},
                data: {
                    keep: {
                        parent: true,
                        leaf: true
                    },
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onDblClick: planTree.moveCaseToRight
                }
            };
            $.fn.zTree.init($("#leftTree"), leftSetting);
            planTreeSetting = {
                data: {
                    simpleData: {
                        enable: true
                    }
                },
                callback: {
                    onClick: planTree.clickPlanTree
                }
            };
        },
        /**
         *获取测试计划tree
         */
        getTestPlanTree: function () {
            var url = "/testPlanController/getPlanTree";
            $.ajax({
                url: url,
                type: "post",
                dataType: "json",
                data: {
                    projectId: projectId
                }, success: function (result) {
                    if (result.success) {
                        var zNodes = result.obj;
                        var leftTree = $.fn.zTree.init($("#testPlanTree"), planTreeSetting, zNodes);
                        var length = zNodes.length;
                        leftTree.selectNode(zNodes[length - 1]);

                    } else {

                    }
                }
            })
        },
        /**
         *点击测试计划tree
         */
        clickPlanTree: function (event, treeId, treeNode) {
            $("#runBuildTest").hide();
            $("#buildTestPlan").hide();
            $("#topTitle").show();
            var testPlanId = treeNode.id;
            $("#testPlanId").val(testPlanId);
            var requestUrl = "/testPlanController/getTestPlanById";
            $.post(requestUrl,
                {
                    testPlanId: testPlanId
                },
                function (result, status) {
                    if (result.success) {
                        var testPlanObj = result.obj;
                        $("#testPlanId").val(testPlanObj.testPlanId);
                        $("#topTestPlanName").text(testPlanObj.testPlanName);
                        var testPlanDetailList = testPlanObj.testPlanDetailList;
                        var lastBuildTest = testPlanObj.lastBuildTest;
                        $("#lastStartTime").text("");
                        $("#lastStatus").empty();
                        $("#topCaseSize").text("");
                        $("#lastPassSizeSize").text("");
                        $("#lastPassRate").text("");
                        $("#lastRunTime").text("");
                        $("#lastLog").empty();
                        $("#runUser").text("");
                        if (null != lastBuildTest) {
                            $("#lastStartTime").text("#" + lastBuildTest.startTime);
                            $("#lastStatus").append(testPlan.statusSwitch(lastBuildTest.status));
                            $("#topCaseSize").text(lastBuildTest.caseSize);
                            $("#lastPassSizeSize").text(lastBuildTest.passCaseSize);
                            $("#lastPassRate").text(lastBuildTest.passRate);
                            $("#lastRunTime").text(lastBuildTest.runTime);
                            $("#lastLog").append("<a onclick='$(\"#myModal\").modal('show')'>查看日志</a>");
                            $("#runUser").text(lastBuildTest.userName);
                        } else {
                            $("#topCaseSize").text(testPlanDetailList.length);
                        }
                        $("#buildTrend").empty();
                        if(null!=testPlanObj.planBuildTestList && testPlanObj.planBuildTestList.length>0) {
                            $("#container-fluid").hide();
                            testPlan.buildTrend(testPlanObj.planBuildTestList);
                        }else {
                            $("#container-fluid").show();
                        }
                    }
                }, "json");
        },
        /**
         * 更新排序
         */
        updateTrsId: function () {
            //设置排序
            var trs = $("#rightCaseTbody>tr");
            for (var int2 = 0; int2 < trs.length; int2++) {
                $(trs[int2].firstChild).text((int2 + 1));
            }
        },
        collaspeAll: function (id) {
            var zTree = $.fn.zTree.getZTreeObj(id);
            zTree.expandAll(false);
        },
        expandAll: function (id) {
            var zTree = $.fn.zTree.getZTreeObj(id);
            zTree.expandAll(true);
            $("#planTree").css("height", $(window).height() - 235);
        },
        /**
         * 获取右侧用例数量
         */
        getRightCaseSize: function () {
            var trs = $("#rightCaseTbody>tr");
            if (trs == null || trs == undefined) {
                return 0;
            }
            return trs.length;
        },
        /**
         * 取消全部用例
         * */
        cancelAllCase: function () {
            $("#rightCaseTable").remove();
            var treeObj = $.fn.zTree.getZTreeObj("leftTree");
            var selectedNodes = treeObj.getNodes();
            var nodes = treeObj.transformToArray(selectedNodes);
            treeObj.showNodes(nodes);
            /**
             * 右侧树节点全部删除
             * */
            var rightTree = $.fn.zTree.getZTreeObj("rightTree");
            var rightNodes = rightTree.getSelectedNodes();
            for (var i = 0, l = rightNodes.length; i < l; i++) {
                rightTree.removeNode(rightNodes[i]);
            }
            //设置文本个数
            var number = planTree.getRightCaseSize();
            $("#rightCaseNumber").text("(" + number + ")");
        },
        /**
         * 移动左侧全部用例到右侧表格
         * */
        moveAllCaseToRight: function () {
            var treeObj = $.fn.zTree.getZTreeObj("leftTree");
            var selectedNodes = treeObj.getNodes();
            var nodes = treeObj.transformToArray(selectedNodes);
            planTree.writeRightCase(nodes);
            treeObj.hideNodes(nodes);
            //执行用例不能为空提示
            // $("#superManCases_Tips").hide();
            //设置文本个数
            var number = planTree.getRightCaseSize();
            $("#rightCaseNumber").text("(" + number + ")");
        },
        /**
         * 移动左侧单个用例到右侧表格
         * */
        moveCaseToRight: function () {
            var leftCaseTree = $.fn.zTree.getZTreeObj("leftTree");
            if (leftCaseTree == null) {
                return
            }
            var selectedNodes = leftCaseTree.getSelectedNodes();

            var nodes = leftCaseTree.transformToArray(selectedNodes);
            if (nodes[0].level == 0 && nodes.length == 1) {
                return
            }
            if (nodes.length > 0) {
                //显示表格
                planTree.writeRightCase(nodes);
                leftCaseTree.hideNodes(nodes);
                var selectedParent = selectedNodes[0].getParentNode();
                planTree.hiddenParentNode(selectedParent, leftCaseTree);
                var rightCaseTree = $.fn.zTree.getZTreeObj("rightTree");
                for (var int = 0; int < nodes.length; int++) {
                    var id = nodes[int].id;
                    //首先获取右侧树是否已经存在父节点了，通过父节点的id去拿
                    //如果没有创建父节点，然后加子节点
                    // var parentId = selectedParent.id;
                    var node = rightCaseTree.getNodeByParam("id", id, null);
                    if (null == node) {
                        rightCaseTree.addNodes(null, nodes);
                    }
                    if (node) {
                        rightCaseTree.showNode(node);
                        planTree.showParentNode(node, "rightTree");
                    }
                }
                //设置文本个数
                var number = planTree.getRightCaseSize();
                $("#rightCaseNumber").text("(" + number + ")");
            }
        },
        /**
         * 取消移动用例
         * */
        cancelCase: function (id) {
            var rightTree = $.fn.zTree.getZTreeObj("rightTree");
            if (rightTree == null) {
                return
            }
            var selectedNodes = rightTree.getNodesByParam("id", id, null);
            if (selectedNodes == null) {
                return
            }

            var nodes = rightTree.transformToArray(selectedNodes);
            //todo 这个地方要处理删掉
            rightTree.hideNodes(nodes);
            var selectedParent = selectedNodes[0].getParentNode();
            //递归隐藏父节点
            planTree.hiddenParentNode(selectedParent, rightTree);

            var leftTree = $.fn.zTree.getZTreeObj("leftTree");
            //id = nodes[0].id;
            var nodes = leftTree.getNodesByParam("id", id, null);
            var nodes = leftTree.transformToArray(nodes);
            // 显示节点的所有子节点
            leftTree.showNodes(nodes);
            // 显示节点的父节点
            planTree.showParentNode(nodes[0], "leftTree");
            //设置文本个数
            var number = planTree.getRightCaseSize();
            $("#superProcessRightNumber").text("(" + number + ")");
        },
        /**
         * 根据已选择用例写入右侧表格
         */
        writeRightCase: function (nodes) {
            var trNumber = $("#rightCaseTbody").children().length;
            if (trNumber == 0) {
                $("#rightCaseTable").empty();
            }
            if (trNumber <= 0) {
                var rightTreeTable = "<table id='rightCaseTable' class='table table-bordered task_apm_tree_table'>" +
                    "<thead>" +
                    "<tr>" +
                    "<th style='width:5% !important'>排序</th>" +
                    "<th style='width:68% !important'>用例标题</th>" +
                    "<th style='width:27% !important'>操作</th>" +
                    "</tr>" +
                    "</thead>" +
                    "<tbody id='rightCaseTbody'>" +

                    "</tbody>" +
                    "</table>";
                $("#caseRightDivId").after(rightTreeTable);
            }
            for (var int = 0; int < nodes.length; int++) {
                //剔除父节点数据
                if (!nodes[int].isParent && !nodes[int].isHidden) {
                    var caseName = planTree.subStringByLength(nodes[int].name, 26);

                    $("#rightCaseTbody").append("<tr id=" + nodes[int].id + ">" +
                        "<td style='text-align:left !important;line-height: 14px !important; width:5% !important;padding:4px !important;text-align: center !important;'>" +
                        "</td>" +
                        "<td style='text-align:left !important;line-height: 14px !important; width:68% !important;padding:4px !important;'>" +
                        // "<form class='jobform' method='post' action='/testcase/caseManage!viewCase.action' target='_blank'>" +
                        // "<input type='hidden' name='type' value='amp'>" +
                        "<input type='hidden' name='testcaseId' value='" + nodes[int].id + "'>" +
                        "<a  class='runStatus rightTreeAstyle' title=" + nodes[int].name + " onclick='jobViewCase(this," + nodes[int].id + ");'>" + caseName + "</a>" +
                        // "</form>" +
                        "</td >" +
                        "<td style='text-align:left !important;line-height: 14px !important; width:27% !important ;padding:4px !important;'>" +
                        "<a href='javascript:void(0)' onclick='planTree.moveCaseToLeft(this);' ><img src='/images/plan/left.png'></a>" +
                        "<a href='javascript:void(0)' onclick='planTree.moveCaseToTop(this);'  style='margin-left: 3px;'><img src='/images/plan/top.png'></a>" +
                        "<a href='javascript:void(0)' onclick='planTree.moveCaseToDown(this);'  style='margin-left: 3px;'><img src='/images/plan/down.png'></a>" +
                        "</td>" +
                        "</tr>");
                }
            }
            planTree.updateTrsId();
        },
        /**
         * 移动右侧用例向上
         */
        moveCaseToTop: function (obj) {
            var tr = $(obj).parents("tr");
            var trPrev = $(obj).parents("tr").prev();
            //当前元素放到上一个元素的前面
            tr.insertBefore(trPrev);
            planTree.updateTrsId();
        },
        /**
         * 移动右侧用例向下
         */
        moveCaseToDown: function (obj) {
            var tr = $(obj).parents("tr");
            var trPrev = $(obj).parents("tr").next();
            //当前元素放到上一个元素的前面
            tr.insertAfter(trPrev);
            planTree.updateTrsId();
        }
        /**
         * 选择右侧用例移动到左侧
         */
        , moveCaseToLeft: function (obj) {
            var tr = $(obj).parents("tr");
            var id = tr.attr("id");
            console.info(tr.children().first().text());
            if ($("#rightCaseTbody>tr").length == "1") {
                $("#rightCaseTable").remove();
            } else {
                tr.remove();
                planTree.updateTrsId();
            }

            //设置文本个数
            var number = planTree.getRightCaseSize();
            $("#rightCaseNumber").text("(" + number + ")");
            planTree.cancelCase(id);

        },
        /**
         * 用于编辑测试计划移动用例到右侧
         * */
        editTestPlanMoveCase: function (testPlanDetailList) {
            var leftTree = $.fn.zTree.getZTreeObj("leftTree");
            testPlanDetailList.forEach(function (v) {
                var node = leftTree.getNodeByParam("id", v.testCaseId, null);
                leftTree.selectNode(node);
                planTree.moveCaseToRight();
            })
        }
        ,
        /**
         * 递归 递归隐藏父节点
         * */
        hiddenParentNode: function (selectedParent, tree) {
            selectedParent;
            if (selectedParent != null) {
                if (selectedParent.children != null) {
                    var childrens = selectedParent.children;
                    var selectedChildrenNum = childrens.length;
                    var hiddenNum = 0;
                    for (var int = 0; int < childrens.length; int++) {
                        if (childrens[int].isHidden == true) {
                            hiddenNum = hiddenNum + 1;
                        }
                    }
                    if (selectedChildrenNum == hiddenNum) {
                        tree.hideNode(selectedParent);
                    }
                    selectedParent;
                    planTree.hiddenParentNode(selectedParent.getParentNode(), tree);
                }
            }
        },
        /**
         * 递归 显示节点的父节点
         * */
        showParentNode: function (node, divId) {
            var treeObj = $.fn.zTree.getZTreeObj(divId);
            if (node != null) {
                if (node.getParentNode() != null) {
                    var parentNode = node.getParentNode();
                    treeObj.showNode(parentNode);
                    planTree.showParentNode(parentNode, divId);
                } else {
                    treeObj.showNode(node);
                }
            }
        },
        /**
         * 监听搜索修改树
         * */
        clickRadio: function (e) {
            lastValue = "";
            planTree.searchNode(e);
        },
        /**
         * 监听搜索
         */
        searchNode: function (e) {
            var zTree = $.fn.zTree.getZTreeObj("leftTree");
            var node = zTree.getNodes()[0];
            zTree.expandNode(node, false, true, false);
            setTimeout(function () {
                var value = $.trim($("#processKey").val());
                if (value === "") {
                    planTree.updateNodes(false);
                    return;
                }
                planTree.updateNodes(false);
                nodeList = zTree.getNodesByParamFuzzy("name", value);
                var searchWithId = zTree.getNodesByParam("id", value);
                nodeList = nodeList.concat(searchWithId);
                for (var i = 0; i < nodeList.length; i++) {
                    if (nodeList[i].getParentNode()) {
                        zTree.expandNode(nodeList[i].getParentNode(), true, false, false);
                    }
                }
                planTree.updateNodes(true);
            }, 200);
        },
        /**
         * 监听搜索修改树
         * */
        updateNodes: function (highlight) {
            var zTree = $.fn.zTree.getZTreeObj("leftTree");
            for (var i = 0, l = nodeList.length; i < l; i++) {
                nodeList[i].highlight = highlight;
                zTree.updateNode(nodeList[i]);
            }
        }
        ,
        clickRadioRight: function (e) {
            lastValue = "";
            planTree.searchNodeRight(e);
        },
        /**
         * 匹配树形菜单节点，高亮显示并展开
         */
        searchNodeRight: function (e) {
            var zTree = $.fn.zTree.getZTreeObj("rightTree");
            var node = zTree.getNodes()[0];
            zTree.expandNode(node, false, true, false);
            setTimeout(function () {
                var value = $.trim($("#processRightKey").val());
                if (value == "") {
                    planTree.updateNodesProcess(false);
                    return;
                }
                planTree.updateNodesProcess(false);
                nodeList = zTree.getNodesByParamFuzzy("name", value);
                for (var i = 0; i < nodeList.length; i++) {
                    if (nodeList[i].getParentNode()) {
                        zTree.expandNode(nodeList[i].getParentNode(), true, false, false);
                    }
                }
                planTree.updateNodesProcess(true);
            }, 200);
        }
        ,
        updateNodesProcess: function (highlight) {
            var zTree = $.fn.zTree.getZTreeObj("rightTree");
            for (var i = 0, l = nodeList.length; i < l; i++) {
                nodeList[i].highlight = highlight;
                zTree.updateNode(nodeList[i]);
            }
        },
        /**
         *截取字符串
         * @param string
         * @returns
         */
        subStringByLength: function (string, l) {
            if (string != null) {
                if (string.length > l) {
                    var substr = string.substring(0, l);
                    return substr + "...";
                } else {
                    return string;
                }
            } else {
                return string;
            }
        }
    }
;

function getFontCss(treeId, treeNode) {
    return (!!treeNode.highlight) ? {color: "#A60000", "font-weight": "bold"} : {
        color: "#333",
        "font-weight": "normal"
    };
}

function filter(zNodes) {
    return (zNodes.isParent == false && zNodes.isHidden == false);
}

processKey = $("#processKey");
processKey.bind("propertychange", planTree.searchNode).bind("input", planTree.searchNode).bind("change", planTree.clickRadio);
processKey = $("#processRightKey");
processKey.bind("propertychange", planTree.searchNodeRight).bind("input", planTree.searchNodeRight).bind("change", planTree.clickRadioRight);




